package com.cms.controller.front;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.cms.Feedback;
import com.cms.entity.Content;
import com.cms.entity.Form;
import com.cms.entity.FormField;
import com.cms.entity.Guestbook;
import com.cms.entity.Site;
import com.cms.routes.RouteMapping;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * Controller - api
 * 
 * 
 * 
 */
@RouteMapping(url = "/api")
public class ApiController extends BaseController {

    /**
     * 点击数
     */
    public void visits() {
        Integer contentId = getParaToInt("contentId");
        if (contentId == null) {
            renderJson(0L);
            return;
        }
        Content content = new Content().dao().findById(contentId);
        Integer visits = content.getVisits();
        visits = visits+1;
        content.setVisits(visits);
        content.update();
        renderJavascript("document.write("+visits+")");
    }
    
    /**
     * 留言
     */
    public void guestbook(){
        if(!validateCaptcha("captcha")){
            renderJson(Feedback.error("验证码错误!"));
            return;
        }
        Site currentSite = getCurrentSite();
        Guestbook guestbook =  getModel(Guestbook.class,"",true); 
        guestbook.setCreateDate(new Date());
        guestbook.setUpdateDate(new Date());
        guestbook.setSiteId(currentSite.getId());
        guestbook.save();
        renderJson(Feedback.success(new HashMap<>()));
    }
    
    /**
     * 表单
     */
    public void form(){
        Integer formId = getParaToInt("formId");
		Form form = new Form().dao().findById(formId);
		List<FormField> formFields = new FormField().dao().findList(formId);
		Record formData = new Record();
		for(FormField formField : formFields){
			String value = getPara(formField.getName());
			formData.set(formField.getName(), value);
		}
		formData.set("createDate", new Date());
		formData.set("updateDate", new Date());
		Db.save(form.getTableName(), formData);
        renderJson(Feedback.success(new HashMap<>()));
    }
}
